{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "15306ece",
   "metadata": {},
   "source": [
    "# 1. 优化ASR接口(草稿) 安装麦克风"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "4228e790",
   "metadata": {},
   "outputs": [],
   "source": [
    "#安装麦克风"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "ee400888",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting PyAudio\n",
      "  Using cached PyAudio-0.2.11.tar.gz (37 kB)\n",
      "Building wheels for collected packages: PyAudio\n",
      "  Building wheel for PyAudio (setup.py): started\n",
      "  Building wheel for PyAudio (setup.py): finished with status 'error'\n",
      "  Running setup.py clean for PyAudio\n",
      "Failed to build PyAudio\n",
      "Installing collected packages: PyAudio\n",
      "    Running setup.py install for PyAudio: started\n",
      "    Running setup.py install for PyAudio: finished with status 'error'\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "  ERROR: Command errored out with exit status 1:\n",
      "   command: 'C:\\ProgramData\\Anaconda3\\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '\"'\"'C:\\\\Users\\\\ASUS\\\\AppData\\\\Local\\\\Temp\\\\pip-install-b4s1rm96\\\\pyaudio_5cd14a06a8bf45e08b85d4598ead2176\\\\setup.py'\"'\"'; __file__='\"'\"'C:\\\\Users\\\\ASUS\\\\AppData\\\\Local\\\\Temp\\\\pip-install-b4s1rm96\\\\pyaudio_5cd14a06a8bf45e08b85d4598ead2176\\\\setup.py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' bdist_wheel -d 'C:\\Users\\ASUS\\AppData\\Local\\Temp\\pip-wheel-h3dvptiw'\n",
      "       cwd: C:\\Users\\ASUS\\AppData\\Local\\Temp\\pip-install-b4s1rm96\\pyaudio_5cd14a06a8bf45e08b85d4598ead2176\\\n",
      "  Complete output (9 lines):\n",
      "  running bdist_wheel\n",
      "  running build\n",
      "  running build_py\n",
      "  creating build\n",
      "  creating build\\lib.win-amd64-3.8\n",
      "  copying src\\pyaudio.py -> build\\lib.win-amd64-3.8\n",
      "  running build_ext\n",
      "  building '_portaudio' extension\n",
      "  error: Microsoft Visual C++ 14.0 or greater is required. Get it with \"Microsoft C++ Build Tools\": https://visualstudio.microsoft.com/visual-cpp-build-tools/\n",
      "  ----------------------------------------\n",
      "  ERROR: Failed building wheel for PyAudio\n",
      "    ERROR: Command errored out with exit status 1:\n",
      "     command: 'C:\\ProgramData\\Anaconda3\\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '\"'\"'C:\\\\Users\\\\ASUS\\\\AppData\\\\Local\\\\Temp\\\\pip-install-b4s1rm96\\\\pyaudio_5cd14a06a8bf45e08b85d4598ead2176\\\\setup.py'\"'\"'; __file__='\"'\"'C:\\\\Users\\\\ASUS\\\\AppData\\\\Local\\\\Temp\\\\pip-install-b4s1rm96\\\\pyaudio_5cd14a06a8bf45e08b85d4598ead2176\\\\setup.py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' install --record 'C:\\Users\\ASUS\\AppData\\Local\\Temp\\pip-record-a53y_i3g\\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\\ProgramData\\Anaconda3\\Include\\PyAudio'\n",
      "         cwd: C:\\Users\\ASUS\\AppData\\Local\\Temp\\pip-install-b4s1rm96\\pyaudio_5cd14a06a8bf45e08b85d4598ead2176\\\n",
      "    Complete output (9 lines):\n",
      "    running install\n",
      "    running build\n",
      "    running build_py\n",
      "    creating build\n",
      "    creating build\\lib.win-amd64-3.8\n",
      "    copying src\\pyaudio.py -> build\\lib.win-amd64-3.8\n",
      "    running build_ext\n",
      "    building '_portaudio' extension\n",
      "    error: Microsoft Visual C++ 14.0 or greater is required. Get it with \"Microsoft C++ Build Tools\": https://visualstudio.microsoft.com/visual-cpp-build-tools/\n",
      "    ----------------------------------------\n",
      "ERROR: Command errored out with exit status 1: 'C:\\ProgramData\\Anaconda3\\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '\"'\"'C:\\\\Users\\\\ASUS\\\\AppData\\\\Local\\\\Temp\\\\pip-install-b4s1rm96\\\\pyaudio_5cd14a06a8bf45e08b85d4598ead2176\\\\setup.py'\"'\"'; __file__='\"'\"'C:\\\\Users\\\\ASUS\\\\AppData\\\\Local\\\\Temp\\\\pip-install-b4s1rm96\\\\pyaudio_5cd14a06a8bf45e08b85d4598ead2176\\\\setup.py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' install --record 'C:\\Users\\ASUS\\AppData\\Local\\Temp\\pip-record-a53y_i3g\\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\\ProgramData\\Anaconda3\\Include\\PyAudio' Check the logs for full command output.\n"
     ]
    }
   ],
   "source": [
    "!pip install PyAudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "126d3839",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting SpeechRecognition\n",
      "  Downloading SpeechRecognition-3.8.1-py2.py3-none-any.whl (32.8 MB)\n",
      "Installing collected packages: SpeechRecognition\n",
      "Successfully installed SpeechRecognition-3.8.1\n",
      "Collecting SpeechRecognition\n",
      "  Downloading SpeechRecognition-3.8.1-py2.py3-none-any.whl (32.8 MB)\n",
      "Installing collected packages: SpeechRecognition\n",
      "Successfully installed SpeechRecognition-3.8.1\n"
     ]
    }
   ],
   "source": [
    "!pip install SpeechRecognition"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "2aa053cd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting pipwin\n",
      "  Using cached pipwin-0.5.2-py2.py3-none-any.whl\n",
      "Requirement already satisfied: six in c:\\programdata\\anaconda3\\lib\\site-packages (from pipwin) (1.15.0)\n",
      "Collecting pySmartDL>=1.3.1\n",
      "  Using cached pySmartDL-1.3.4-py3-none-any.whl (20 kB)\n",
      "Collecting js2py\n",
      "  Using cached Js2Py-0.71-py3-none-any.whl (1.0 MB)\n",
      "Requirement already satisfied: packaging in c:\\programdata\\anaconda3\\lib\\site-packages (from pipwin) (20.9)\n",
      "Collecting pyprind\n",
      "  Using cached PyPrind-2.11.3-py2.py3-none-any.whl (8.4 kB)\n",
      "Requirement already satisfied: requests in c:\\programdata\\anaconda3\\lib\\site-packages (from pipwin) (2.25.1)\n",
      "Requirement already satisfied: beautifulsoup4>=4.9.0 in c:\\programdata\\anaconda3\\lib\\site-packages (from pipwin) (4.9.3)\n",
      "Collecting docopt\n",
      "  Using cached docopt-0.6.2-py2.py3-none-any.whl\n",
      "Requirement already satisfied: soupsieve>1.2 in c:\\programdata\\anaconda3\\lib\\site-packages (from beautifulsoup4>=4.9.0->pipwin) (2.2.1)\n",
      "Collecting pyjsparser>=2.5.1\n",
      "  Using cached pyjsparser-2.7.1-py3-none-any.whl\n",
      "Collecting tzlocal>=1.2\n",
      "  Using cached tzlocal-4.2-py3-none-any.whl (19 kB)\n",
      "Collecting backports.zoneinfo\n",
      "  Using cached backports.zoneinfo-0.2.1-cp38-cp38-win_amd64.whl (38 kB)\n",
      "Collecting pytz-deprecation-shim\n",
      "  Using cached pytz_deprecation_shim-0.1.0.post0-py2.py3-none-any.whl (15 kB)\n",
      "Requirement already satisfied: tzdata in c:\\programdata\\anaconda3\\lib\\site-packages (from tzlocal>=1.2->js2py->pipwin) (2022.1)\n",
      "Requirement already satisfied: pyparsing>=2.0.2 in c:\\programdata\\anaconda3\\lib\\site-packages (from packaging->pipwin) (2.4.7)\n",
      "Requirement already satisfied: idna<3,>=2.5 in c:\\programdata\\anaconda3\\lib\\site-packages (from requests->pipwin) (2.10)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\programdata\\anaconda3\\lib\\site-packages (from requests->pipwin) (1.26.4)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in c:\\programdata\\anaconda3\\lib\\site-packages (from requests->pipwin) (2020.12.5)\n",
      "Requirement already satisfied: chardet<5,>=3.0.2 in c:\\programdata\\anaconda3\\lib\\site-packages (from requests->pipwin) (4.0.0)\n",
      "Installing collected packages: backports.zoneinfo, pytz-deprecation-shim, tzlocal, pyjsparser, pySmartDL, pyprind, js2py, docopt, pipwin\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "ERROR: Could not install packages due to an OSError: [WinError 5] 拒绝访问。: 'C:\\\\ProgramData\\\\Anaconda3\\\\Lib\\\\site-packages\\\\backports\\\\__init__.py'\n",
      "Consider using the `--user` option or check the permissions.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "!pip install pipwin"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "4b29815f",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "'pipwin' 不是内部或外部命令，也不是可运行的程序\n",
      "或批处理文件。\n"
     ]
    }
   ],
   "source": [
    "!pipwin install PyAudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3012b32a",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ef043ac",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca26c02e",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e37ad5b2",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d1a548ff",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3fdeaf07",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30239a64",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "715397ea",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8c3e8992",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb878516",
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        timer = time.time\n",
    "\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "# 获取access_token的函数\n",
    "def fetch_token(API_KEY,SECRET_KEY):\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request('http://aip.baidubce.com/oauth/2.0/token', post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "    result = json.loads(result_str)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "# 语音识别函数      \n",
    "def asr(token,AUDIO_FILE,CUID='123456PYTHON',DEV_PID=1537,RATE=16000):\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "    params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "    params_query = urlencode(params);\n",
    "    headers = {\n",
    "        'Content-Type': 'audio/' + AUDIO_FILE[-3:] + '; rate=' + str(RATE),\n",
    "        'Content-Length': length\n",
    "    }\n",
    "\n",
    "    url = 'http://vop.baidu.com/server_api' + \"?\" + params_query\n",
    "    req = Request('http://vop.baidu.com/server_api' + \"?\" + params_query, speech_data, headers)\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "    print(result_str)\n",
    "    with open(\"result.txt\", \"w\") as of:\n",
    "        of.write(result_str)\n",
    "    return result_str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "63c624c9",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7ab7bca9",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6be8f4de",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "d8de2d22",
   "metadata": {},
   "source": [
    "# 2.优化百度ASR接口"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "24da0be8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# zhichao : 百度密钥\n",
    "API_KEY = 'smxkOHWjqLVljEmIry5vuSYI'\n",
    "SECRET_KEY = 'ky3FZeSSDurxLyLLqZ2kPaEnts9NH1W1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "728fc25d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 调用bdasr\n",
    "from bdasr import fetch_token,asr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "52735b46",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SUCCESS WITH TOKEN: 24.7f33e4d2c493ca8111fe01f0d7e2c9d6.2592000.1656512152.282335-19331335 ; EXPIRES IN SECONDS: 2592000\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'24.7f33e4d2c493ca8111fe01f0d7e2c9d6.2592000.1656512152.282335-19331335'"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "xu_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52c3ea37",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 准备音频文件（还没下载麦克风，需下麦克风） \n",
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将16k0.0数据保存到wav文件中\n",
    "with open(\"16k0.0.pcm\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "546d06e1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e1fcbc2",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "2a721cec",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 识别1.wav（你好啊）的语音文字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "909193ff",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Request time cost 0.361960\n",
      "{\"corpus_no\":\"7103533020167552604\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"好，北京科技馆。\"],\"sn\":\"536498414941653920165\"}\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'{\"corpus_no\":\"7103533020167552604\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"好，北京科技馆。\"],\"sn\":\"536498414941653920165\"}\\n'"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "asr(token = xu_token, AUDIO_FILE = '1.wav')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "94530917",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Request time cost 0.229271\n",
      "{\"corpus_no\":\"7103533028579201938\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"好，北京科技馆。\"],\"sn\":\"551485279991653920167\"}\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'{\"corpus_no\":\"7103533028579201938\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"好，北京科技馆。\"],\"sn\":\"551485279991653920167\"}\\n'"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "asr(xu_token,'1.wav')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d4818c2",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f35c0a1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "289ccbc1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "c180f12c",
   "metadata": {},
   "source": [
    "# 开始"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "b2b02447",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# 语音识别1.wav  你好 北京科技馆（识别自己的录音文件）\n",
    "# zhichao : 百度密钥\n",
    "API_KEY = 'smxkOHWjqLVljEmIry5vuSYI'\n",
    "SECRET_KEY = 'ky3FZeSSDurxLyLLqZ2kPaEnts9NH1W1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "bbd269f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "from bdasr import fetch_token,asr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "da7d8415",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SUCCESS WITH TOKEN: 24.1005bd30edcb040b213341debecfc3df.2592000.1656512322.282335-19331335 ; EXPIRES IN SECONDS: 2592000\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'24.1005bd30edcb040b213341debecfc3df.2592000.1656512322.282335-19331335'"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "xu_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7e57e434",
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "310fe8fe",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Request time cost 0.265675\n",
      "{\"corpus_no\":\"7103533707400213968\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"好，北京科技馆。\"],\"sn\":\"395975562751653920325\"}\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'好，北京科技馆。'"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "asr_output = eval(asr(xu_token,'1.wav'))['result'][0]\n",
    "asr_output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ccabf592",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75dcf66e",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85053a76",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "89786a63",
   "metadata": {},
   "source": [
    "# 3.1连接图灵机器人（文字问-文字答）\n",
    "接口\n",
    "post\n",
    "请求参数\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2252d33b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 学生实践\n",
    "import requests,json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "914ca96f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'reqType': 0, 'perception': {'inputText': {'text': '苹果英语怎么说'}}, 'userInfo': {'apiKey': 'd5d5bb66f66d4da8bedb378df7adfa70', 'userId': '000001'}}\n",
      "{\"reqType\": 0, \"perception\": {\"inputText\": {\"text\": \"\\u82f9\\u679c\\u82f1\\u8bed\\u600e\\u4e48\\u8bf4\"}}, \"userInfo\": {\"apiKey\": \"d5d5bb66f66d4da8bedb378df7adfa70\", \"userId\": \"000001\"}}\n"
     ]
    }
   ],
   "source": [
    "#  字典dict不等于json  所以字典dict json=json.dumps\n",
    "TL_KEY = \"d5d5bb66f66d4da8bedb378df7adfa70\"\n",
    "TL_URL = \"http://openapi.turingapi.com/openapi/api/v2\"\n",
    "payload={\n",
    "    \"reqType\":0,\n",
    "    \"perception\": {\n",
    "        \"inputText\": {\n",
    "            \"text\": \"苹果英语怎么说\"\n",
    "         },\n",
    "    },\n",
    "\n",
    "    \"userInfo\": {\n",
    "        \"apiKey\": TL_KEY,\n",
    "        \"userId\": \"000001\"\n",
    "    }\n",
    "}\n",
    "\n",
    "print(payload)\n",
    "print(json.dumps(payload))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "6154435a",
   "metadata": {},
   "outputs": [],
   "source": [
    "res = requests.post(TL_URL,data = payload)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "497d39c6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Response [200]>"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "f21fadc0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'intent': {'code': 4000},\n",
       " 'results': [{'groupType': 0,\n",
       "   'resultType': 'text',\n",
       "   'values': {'text': '请求参数缺失或格式错误!'}}]}"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af18e9dd",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8837fe54",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab542ffe",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1daea27e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 改进（正确） apple 1.0\n",
    "import requests,json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f1957bc5",
   "metadata": {},
   "outputs": [],
   "source": [
    "TL_KEY = \"d5d5bb66f66d4da8bedb378df7adfa70\"\n",
    "TL_URL = \"http://openapi.turingapi.com/openapi/api/v2\"\n",
    "payload={\n",
    "    \"reqType\":0,\n",
    "    \"perception\": {\n",
    "        \"inputText\": {\n",
    "            \"text\": \"苹果英语怎么说\"\n",
    "         },\n",
    "    },\n",
    "\n",
    "    \"userInfo\": {\n",
    "        \"apiKey\": TL_KEY,\n",
    "        \"userId\": \"000001\"\n",
    "    }\n",
    "}\n",
    "\n",
    "res = requests.post(TL_URL,data = json.dumps(payload))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "448f0970",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Response [200]>"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "56d45c5f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'intent': {'actionName': '', 'code': 10020, 'intentName': ''},\n",
       " 'results': [{'groupType': 1,\n",
       "   'resultType': 'text',\n",
       "   'values': {'text': 'apple'}}]}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "188e7143",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6a406064",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1a55dd77",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "51d0fd39",
   "metadata": {},
   "outputs": [],
   "source": [
    "# apple 2.0\n",
    "import requests,json\n",
    "TL_KEY = \"d5d5bb66f66d4da8bedb378df7adfa70\"\n",
    "TL_URL = \"http://openapi.turingapi.com/openapi/api/v2\"\n",
    "payload={\n",
    "    \"reqType\":0,\n",
    "    \"perception\": {\n",
    "        \"inputText\": {\n",
    "            \"text\": \"苹果英语怎么说\"\n",
    "         },\n",
    "    },\n",
    "\n",
    "    \"userInfo\": {\n",
    "        \"apiKey\": TL_KEY,\n",
    "        \"userId\": \"000001\"\n",
    "    }\n",
    "}\n",
    "\n",
    "res = requests.post(TL_URL,data = json.dumps(payload))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "4b484ca3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Response [200]>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "bdbb2b5b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'intent': {'actionName': '', 'code': 10020, 'intentName': ''},\n",
       " 'results': [{'groupType': 1,\n",
       "   'resultType': 'text',\n",
       "   'values': {'text': 'apple'}}]}"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "371d1e6d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75e6fd8d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3d402af",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "7e0813a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 问天气\n",
    "import requests,json\n",
    "TL_KEY = \"d5d5bb66f66d4da8bedb378df7adfa70\"\n",
    "TL_URL = \"http://openapi.turingapi.com/openapi/api/v2\"\n",
    "payload={\n",
    "    \"reqType\":0,\n",
    "    \"perception\": {\n",
    "        \"inputText\": {\n",
    "            \"text\": \"广州今天的天气怎么样\"\n",
    "         },\n",
    "    },\n",
    "\n",
    "    \"userInfo\": {\n",
    "        \"apiKey\": TL_KEY,\n",
    "        \"userId\": \"000001\"\n",
    "    }\n",
    "}\n",
    "\n",
    "res = requests.post(TL_URL,data = json.dumps(payload))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "5c15f149",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Response [200]>"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "ddc9328e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'intent': {'actionName': '',\n",
       "  'code': 10008,\n",
       "  'intentName': '',\n",
       "  'parameters': {'date': '2022-05-30', 'city': '广州'}},\n",
       " 'results': [{'groupType': 1,\n",
       "   'resultType': 'text',\n",
       "   'values': {'text': '广州:周一 05月30日,雷阵雨 持续无风向,最低气温25度，最高气温33度。'}}]}"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3967b51d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02eb2835",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7e274b2",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "e69146dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 讲笑话\n",
    "import requests,json\n",
    "TL_KEY = \"d5d5bb66f66d4da8bedb378df7adfa70\"\n",
    "TL_URL = \"http://openapi.turingapi.com/openapi/api/v2\"\n",
    "payload={\n",
    "    \"reqType\":0,\n",
    "    \"perception\": {\n",
    "        \"inputText\": {\n",
    "            \"text\": \"讲个笑话吧\"\n",
    "         },\n",
    "    },\n",
    "\n",
    "    \"userInfo\": {\n",
    "        \"apiKey\": TL_KEY,\n",
    "        \"userId\": \"000001\"\n",
    "    }\n",
    "}\n",
    "\n",
    "res = requests.post(TL_URL,data = json.dumps(payload))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "c263fd44",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Response [200]>"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "8ca3535d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'intent': {'actionName': '', 'code': 10006, 'intentName': ''},\n",
       " 'results': [{'groupType': 1,\n",
       "   'resultType': 'text',\n",
       "   'values': {'text': '本人大龄单身女青年一枚 好不容易有人约我今天去爬山 昨天一点前兆都木有呢 今天早上还在睡梦中难受醒了 居然发烧了 我在犹豫 我是去还是不去呢 ?几个?-'}}]}"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7316ba9d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "135aca21",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80a1530f",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "82804918",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 找酒店\n",
    "import requests,json\n",
    "TL_KEY = \"d5d5bb66f66d4da8bedb378df7adfa70\"\n",
    "TL_URL = \"http://openapi.turingapi.com/openapi/api/v2\"\n",
    "payload={\n",
    "    \"reqType\":0,\n",
    "    \"perception\": {\n",
    "        \"inputText\": {\n",
    "            \"text\": \"附近的酒店\"\n",
    "         },\n",
    "        \"inputImage\":{\n",
    "            \"url\":\"imageUrl\"\n",
    "        },\n",
    "        \"selfInfo\":{\n",
    "            \"location\":{\n",
    "                \"city\":\"北京\",\n",
    "                \"province\":\"北京\",\n",
    "                \"street\":\"信息路\"\n",
    "            }\n",
    "        }\n",
    "    },\n",
    "    \"userInfo\": {\n",
    "        \"apiKey\": TL_KEY,\n",
    "        \"userId\": \"000001\"\n",
    "    }\n",
    "}\n",
    "\n",
    "res = requests.post(TL_URL,data = json.dumps(payload))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "e8fd8867",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Response [200]>"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "c40a23eb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'intent': {'actionName': '',\n",
       "  'code': 1100,\n",
       "  'intentName': '',\n",
       "  'parameters': {'nearby_place': '酒店'}},\n",
       " 'results': [{'groupType': 0,\n",
       "   'resultType': 'text',\n",
       "   'values': {'text': '正在查找附近酒店，请稍等'}}]}"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f4797f00",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7105ee62",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b649de5c",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "b9c3cccd",
   "metadata": {},
   "source": [
    "# 3.2连接图灵机器人（语音问-文字答）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "731b8649",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1.0无麦克风，录不了音频 \n",
    "# zhichao : 百度密钥\n",
    "API_KEY = 'smxkOHWjqLVljEmIry5vuSYI'\n",
    "SECRET_KEY = 'ky3FZeSSDurxLyLLqZ2kPaEnts9NH1W1'\n",
    "\n",
    "# 调用bdasr\n",
    "from bdasr import fetch_token,asr\n",
    "\n",
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "xu_token\n",
    "\n",
    "import requests,json\n",
    "TL_KEY = \"d5d5bb66f66d4da8bedb378df7adfa70\"\n",
    "TL_URL = \"http://openapi.turingapi.com/openapi/api/v2\"\n",
    "\n",
    "\n",
    "# 1.录制音频\n",
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将音频文件保持到wav件中\n",
    "with open(\"1.wav\",\"wb\") as f:\n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "\n",
    "\n",
    "    \n",
    "# 2.语音识别\n",
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "asr_output = eval(asr(xu_token,\"1.wav\"))['result'][0]\n",
    "# 3.图灵API\n",
    "TL_API(TL_KEY,asr_output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8f179ba1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fce4990d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7c79ceac",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "af927899",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2.0（改进）----不用麦克风录音，直接用语音文件问【而且还要import def 这些调用】\n",
    "import requests,json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "27ee7d0a",
   "metadata": {},
   "outputs": [],
   "source": [
    "TL_KEY = \"d5d5bb66f66d4da8bedb378df7adfa70\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "8e8ab8fc",
   "metadata": {},
   "outputs": [],
   "source": [
    "def TL_API(key,text):\n",
    "    TL_URL = \"http://openapi.turingapi.com/openapi/api/v2\"\n",
    "\n",
    "    payload={\n",
    "        \"reqType\":0,\n",
    "        \"perception\": {\n",
    "            \"inputText\": {\n",
    "                \"text\": text\n",
    "            },\n",
    "        },\n",
    "        \"userInfo\": {\n",
    "            \"apiKey\": TL_KEY,\n",
    "            \"userId\": \"000001\"\n",
    "        }\n",
    "    }\n",
    "    res = requests.post(TL_URL,data = json.dumps(payload))\n",
    "    return res.json()['results'][0]['values']['text']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "cb28b52e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SUCCESS WITH TOKEN: 24.08203b7814e72aff616db9b1877a033a.2592000.1656513581.282335-19331335 ; EXPIRES IN SECONDS: 2592000\n",
      "SUCCESS WITH TOKEN: 24.08203b7814e72aff616db9b1877a033a.2592000.1656513581.282335-19331335 ; EXPIRES IN SECONDS: 2592000\n",
      "Request time cost 0.296430\n",
      "{\"corpus_no\":\"7103539101732950323\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"好，北京科技馆。\"],\"sn\":\"561968211811653921581\"}\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'好的'"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "\n",
    "# zhichao : 百度密钥\n",
    "API_KEY = 'smxkOHWjqLVljEmIry5vuSYI'\n",
    "SECRET_KEY = 'ky3FZeSSDurxLyLLqZ2kPaEnts9NH1W1'\n",
    "\n",
    "# 调用bdasr\n",
    "from bdasr import fetch_token,asr\n",
    "\n",
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "xu_token\n",
    "\n",
    "import requests,json\n",
    "TL_KEY = \"d5d5bb66f66d4da8bedb378df7adfa70\"\n",
    "TL_URL = \"http://openapi.turingapi.com/openapi/api/v2\"\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "    \n",
    "# 2. 语音识别\n",
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "asr_output = eval(asr(xu_token,'1.wav'))['result'][0]\n",
    "\n",
    "# 3. 图灵API\n",
    "TL_API(TL_KEY,asr_output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7b65851",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a72cf289",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17f20ea6",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "557215ee",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3.0（改进）----不用麦克风录音，直接用语音文件问【而且还要import def 这些调用】\n",
    "# 问16k.pcm(北京科技管)\n",
    "import requests,json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "82ce863a",
   "metadata": {},
   "outputs": [],
   "source": [
    "TL_KEY = \"d5d5bb66f66d4da8bedb378df7adfa70\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "6e6ba7c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "def TL_API(key,text):\n",
    "    TL_URL = \"http://openapi.turingapi.com/openapi/api/v2\"\n",
    "\n",
    "    payload={\n",
    "        \"reqType\":0,\n",
    "        \"perception\": {\n",
    "            \"inputText\": {\n",
    "                \"text\": text\n",
    "            },\n",
    "        },\n",
    "        \"userInfo\": {\n",
    "            \"apiKey\": TL_KEY,\n",
    "            \"userId\": \"000001\"\n",
    "        }\n",
    "    }\n",
    "    res = requests.post(TL_URL,data = json.dumps(payload))\n",
    "    return res.json()['results'][0]['values']['text']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "c888fe3a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SUCCESS WITH TOKEN: 24.fd399450ef94a6dcd5ee27a1b18fa238.2592000.1656513972.282335-19331335 ; EXPIRES IN SECONDS: 2592000\n",
      "SUCCESS WITH TOKEN: 24.fd399450ef94a6dcd5ee27a1b18fa238.2592000.1656513972.282335-19331335 ; EXPIRES IN SECONDS: 2592000\n",
      "Request time cost 0.639680\n",
      "{\"corpus_no\":\"7103540781033355484\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"北京科技馆。\"],\"sn\":\"622346826351653921972\"}\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'具体地址在哪里？'"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "\n",
    "# zhichao : 百度密钥\n",
    "API_KEY = 'smxkOHWjqLVljEmIry5vuSYI'\n",
    "SECRET_KEY = 'ky3FZeSSDurxLyLLqZ2kPaEnts9NH1W1'\n",
    "\n",
    "# 调用bdasr\n",
    "from bdasr import fetch_token,asr\n",
    "\n",
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "xu_token\n",
    "\n",
    "import requests,json\n",
    "TL_KEY = \"d5d5bb66f66d4da8bedb378df7adfa70\"\n",
    "TL_URL = \"http://openapi.turingapi.com/openapi/api/v2\"\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "    \n",
    "# 2. 语音识别\n",
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "asr_output = eval(asr(xu_token,'16k.pcm'))['result'][0]\n",
    "\n",
    "# 3. 图灵API\n",
    "TL_API(TL_KEY,asr_output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "09f96166",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed89bc20",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "81e0c142",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "af0612d8",
   "metadata": {},
   "source": [
    "# 4.语音合成测试(文字变语音)  \n",
    "## 生成新音频.mp3-然后可以用jupyter直接播放新音频.mp3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "efe0faa5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "import sys\n",
    "import json\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    from urllib.parse import quote_plus\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib import quote_plus\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "API_KEY = '4E1BG9lTnlSeIf1NQFlrSq6h'\n",
    "SECRET_KEY = '544ca4657ba8002e3dea3ac2f5fdd241'\n",
    "\n",
    "TEXT = \"欢迎使用百度语音合成。\"\n",
    "\n",
    "# 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，\n",
    "# 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美 \n",
    "PER = 4\n",
    "# 语速，取值0-15，默认为5中语速\n",
    "SPD = 5\n",
    "# 音调，取值0-15，默认为5中语调\n",
    "PIT = 5\n",
    "# 音量，取值0-9，默认为5中音量\n",
    "VOL = 5\n",
    "# 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav\n",
    "AUE = 6\n",
    "\n",
    "FORMATS = {3: \"mp3\", 4: \"pcm\", 5: \"pcm\", 6: \"wav\"}\n",
    "FORMAT = FORMATS[AUE]\n",
    "\n",
    "CUID = \"123456PYTHON\"\n",
    "\n",
    "TTS_URL = 'http://tsn.baidu.com/text2audio'\n",
    "\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "SCOPE = 'audio_tts_post'  # 有此scope表示有tts能力，没有请在网页里勾选\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    print(\"fetch token begin\")\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req, timeout=5)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "#    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "#    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if not SCOPE in result['scope'].split(' '):\n",
    "            raise DemoError('scope is not correct')\n",
    "#        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "def tts(token,TEXT):\n",
    "    token = fetch_token()\n",
    "    tex = quote_plus(TEXT)  # 此处TEXT需要两次urlencode\n",
    "    print(tex)\n",
    "    params = {'tok': token, 'tex': tex, 'per': PER, 'spd': SPD, 'pit': PIT, 'vol': VOL, 'aue': AUE, 'cuid': CUID,\n",
    "              'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数\n",
    "\n",
    "    data = urlencode(params)\n",
    "    print('test on Web Browser' + TTS_URL + '?' + data)\n",
    "\n",
    "    req = Request(TTS_URL, data.encode('utf-8'))\n",
    "    has_error = False\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "\n",
    "        headers = dict((name.lower(), value) for name, value in f.headers.items())\n",
    "\n",
    "        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "        has_error = True\n",
    "\n",
    "    save_file = \"error.txt\" if has_error else 'result.' + FORMAT\n",
    "    with open(save_file, 'wb') as of:\n",
    "        of.write(result_str)\n",
    "\n",
    "    if has_error:\n",
    "        if (IS_PY3):\n",
    "            result_str = str(result_str, 'utf-8')\n",
    "        print(\"tts api  error:\" + result_str)\n",
    "\n",
    "    print(\"result saved as :\" + save_file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "id": "c14e64a5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "fetch token begin\n",
      "%E6%AC%A2%E8%BF%8E%E4%BD%BF%E7%94%A8%E7%99%BE%E5%BA%A6%E8%AF%AD%E9%9F%B3%E5%90%88%E6%88%90%E3%80%82\n",
      "test on Web Browserhttp://tsn.baidu.com/text2audio?tok=24.671b7c9da928cc3235d7dda84f365ff8.2592000.1655350380.282335-10854623&tex=%25E6%25AC%25A2%25E8%25BF%258E%25E4%25BD%25BF%25E7%2594%25A8%25E7%2599%25BE%25E5%25BA%25A6%25E8%25AF%25AD%25E9%259F%25B3%25E5%2590%2588%25E6%2588%2590%25E3%2580%2582&per=4&spd=5&pit=5&vol=5&aue=6&cuid=123456PYTHON&lan=zh&ctp=1\n",
      "tts api  error:{\"err_detail\":\"16: Open api characters limit reached\",\"err_msg\":\"16: Open api characters limit reached\",\"err_no\":502,\"err_subcode\":16,\"tts_logid\":2883970738}\n",
      "\n",
      "result saved as :error.txt\n"
     ]
    }
   ],
   "source": [
    "tts(xu_token,TEXT)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6021271e",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c509a17f",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d1d09636",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "ae9ed1a3",
   "metadata": {},
   "source": [
    "# 5.在jupyter上播放音频文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "22ddf711",
   "metadata": {},
   "outputs": [
    {
     "ename": "ModuleNotFoundError",
     "evalue": "No module named 'pydub'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-26-e8446920a920>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32mfrom\u001b[0m \u001b[0mpydub\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mAudioSegment\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      2\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mpydub\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mplayback\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mplay\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[0msong\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mAudioSegment\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfrom_wav\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'1.wav'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'pydub'"
     ]
    }
   ],
   "source": [
    "from pydub import AudioSegment\n",
    "\n",
    "from pydub.playback import play\n",
    "\n",
    "song = AudioSegment.from_wav('1.wav')\n",
    "\n",
    "play(song)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28e9319f",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd3b6cea",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a30e18cb",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "74d25e1e",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "5886c91b",
   "metadata": {},
   "source": [
    "# 6.智能对话机器人最终版\n",
    "## 【语音问-语音答】"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44281ca7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1.录制音频\n",
    "import speech_recognition\n",
    "from pydub import AudioSegment\n",
    "from pydub.playback import play\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "    \n",
    "# 将音频文件保持到wav件中\n",
    "with open(\"2.wav\",\"wb\") as f:\n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "    \n",
    "# 2.语音识别\n",
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "asr_output = eval(asr(xu_token,\"2.wav\"))['result'][0]\n",
    "\n",
    "# 3.图灵API\n",
    "TL_result = TL_API(TL_KEY,asr_output)\n",
    "\n",
    "# 4.语音合成（tts）--> 产生result.wav\n",
    "tts(xu_token,TL_result)\n",
    "\n",
    "# 5.在jupyter播放\n",
    "song = AudioSegment.from_wav('result.wav')\n",
    "play(song)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e5a5ab00",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
